package com.sptpc.demo.controller;

import com.sptpc.demo.global.response.GlobalResponse;
import com.sptpc.demo.model.Category;
import com.sptpc.demo.service.ICategoryService;
import com.sptpc.demo.vo.CategoryWithDrinksVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
@Api(value = "CategoryController", tags = {"饮品分类管理"})
public class CategoryController {
    @Autowired
    public ICategoryService categoryService;
//
//    /**
//     * 查询所有
//     * @return
//     */
    @ApiOperation(value = "查询所有分类信息")
    @GetMapping("/")
    public GlobalResponse getAll() {
       List<Category> allCategories= categoryService.getAllCategories();
            return GlobalResponse.success(allCategories);

    }


//查询分类id一致的饮品
@ApiOperation(value = "查询指定分类信息", notes = "必须在url上提交id")
    @GetMapping("/{id}")
    public List<CategoryWithDrinksVo> getWithDrinksById(@PathVariable Long id){
        return categoryService.getCategoryWithDrinks(id);
    }

//    /**
//     * 新建
//     */
    @PostMapping("/")
    public Category addNewDrink(@RequestBody @Valid Category category,
                             BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        } else {
            log.info("新增分类：{}", category);
            categoryService.addNewCategory(category);
            return category;
        }
    }
//
//    // put /category/
    @PutMapping("/")
    public Category modifyCategory(@RequestBody Category request) {
        log.info("要修改的分类：{}", request);

        // 1、通过id查询出分类
        Category category = categoryService.getCategoryById(request.getId());
        // 2、复制前端要修改的属性
        BeanUtils.copyProperties(request, category);
        // 3、更新数据库
        categoryService.updateCategory(category);

        return category;
    }
    @ApiOperation(value = "删除分类信息", notes = "必须在url上提交id")
    @DeleteMapping("/{id}")
    public String deleteCategory(@PathVariable Long id) {
        log.info("要删除的分类id：{}", id);
        categoryService.deleteCategoryById(id);
        return "删除操作成功";
    }


}
